﻿#!/usr/bin/env python
# -*- coding:utf-8 -*-

'thread introduction'

__author__='zhaoxp'

import time,threading

balance=0
lock=threading.Lock()

def change_it(n):
	global balance
	balance=balance+n
	balance=balance-n
	
def run_thread(n):
	for i in range(100000):
		change_it(n)
		
def run_thread2(n):
	for i in range(100000):
		lock.acquire()
		try:
			change_it(n)
		finally:
			lock.release()

def main1():
	t1=threading.Thread(target=run_thread,args=(5,))
	t2=threading.Thread(target=run_thread,args=(8,))
	t1.start()
	t2.start()
	t1.join()
	t2.join()
	
def main2():
	t1=threading.Thread(target=run_thread2,args=(5,))
	t2=threading.Thread(target=run_thread2,args=(8,))
	t1.start()
	t2.start()
	t1.join()
	t2.join()
			
if __name__=='__main__':
	main1()
	print 'balance is %s' % balance
	balance=0
	main2()
	print 'balance is %s' % balance
